/*
 * @Author: szx
 * @Date: 2023-03-29 19:18:38
 * @LastEditTime: 2023-03-29 20:03:31
 * @Description: 
 * @FilePath: \learn\fullstackopen\part3\models\person.js
 */
/*
 * @Author: szx
 * @Date: 2023-03-29 18:58:30
 * @LastEditTime: 2023-03-29 19:17:18
 * @Description: 
 * @FilePath: \learn\fullstackopen\part3\mongo.js
 */
const mongoose = require('mongoose')

const url = process.env.MONGODB_URI

console.log('connecting to', url)

mongoose.connect(url)
    .then(result => {
        console.log('connected to MongoDB')
    })
    .catch((error) => {
        console.log('error connecting to MongoDB:', error.message)
    })

const personSchema = new mongoose.Schema({
    name: {
        type: String,
        minLength: 3,
        require: true,
    },
    number: {
        type: String,
        validate: {
            validator: function (v) {
                return /\d{3}-\d{3}-\d{4}/.test(v);
            },
            message: props => `${props.value} is not a valid phone number!`
        },
        required: [true, 'User phone number required']
    }
})

personSchema.set('toJSON', {
    transform: (document, returnedObject) => {
        returnedObject.id = returnedObject._id.toString()
        delete returnedObject._id
        delete returnedObject.__v
    }
})
module.exports = mongoose.model('PhoneBook', personSchema)

